/*
 * @Author: qgn
 * @Date: 2021-07-28 23:34:24
 * @LastEditors: qgn
 * @LastEditTime: 2021-07-29 00:04:27
 * @Description: file content
 * @FilePath: /admin-template-study/mock/mock-server.js
 */

const chokidar = require("chokidar"); // 监听文件夹发生变化
const bodyParser = require("body-parser"); // 请求中间件，解析http请求，是express的配置项之一
const chalk = require("chalk"); // 改变后台返回文字样式
const path = require("path"); // 处理文件路径
const Mock = require("mockjs");

// process.cwd() 获取前目录
const mockDir = path.join(process.cwd(), "mock"); // process.cwd() 返回当前工作脚本的工作路径

function registerRoutes(app) {
  let mockLastIndex;

  const { mocks } = require("./index");

  const mocksForServe = mocks.map((route) => {
    return responseFake(route.url, route.type, route.response);
  });

  for (const mock of mocksForServe) {
    console.log("查看此时的mock数据是什么,app又是什么", mock, app);
    app[mock.type](mock.url, mock.response);
    mockLastIndex = app._router.stack.length;
  }

  // Object.keys()方法会返回一个由给定对象的自身可枚举属性组成的数组
  const mockRoutesLength = Object.keys(mocksForServe).lenghth;

  console.log(
    "查看mock路由中mock的数据是什么",
    mockRoutesLength,
    mockRoutesLength
  );

  return {
    mockForServeLength: mockRoutesLength,
    mockStartIndex: mockLastIndex - mockRoutesLength,
  };
}

function unregisterModule() {
  Object.keys(require.cache).forEach((i) => {
    if (i.includes(mockDir)) {
      console.log("当前删除配置对象的数据", i);
      delete require.cache[require.resolve(i)];
    }
  });
}

// for mock server
const responseFake = (url, type, respond) => {
  console.log(
    "当前正则出来的是什么",
    new RegExp(`${process_env.VUE_APP_BASE_API}${url}`)
  );
  return {
    url: new RegExp(`${process_env.VUE_APP_BASE_API}${url}`),
    type: type || "get",
    response(req, res) {
      console.log("request invoke", req.path); // 请求过来的地址
      res.join(
        Mock.mock(respond instanceof Function ? respond(req, res) : respond)
      );
    },
  };
};

module.exports = (app) => {
  app.use(bodyParser.json()); // bodyParser对请求体进行解析为json格式
  app.use(
    bodyParser.urlencoded({
      // 解析文本格式
      extended: true,
    })
  );

  const mockRoutes = registerRoutes(app);
  console.log("查看registerRoutes的作用", app, mockRoutes);

  var mockRoutesLength = mockRoutes.mockRoutesLength;
  var mockStartIndex = mockRoutes.mockStartIndec;

  console.log(
    "看看mock路由的这两个对象是什么",
    mockRoutesLength,
    mockStartIndex
  );
};
